//
//  ZKPageCarsouelView.m
//  朱凯的工具箱
//
//  Created by pro on 17/2/21.
//  Copyright © 2017年 zhukai. All rights reserved.
//

#import "ZKPageCarsouelView.h"

@interface ZKPageCarsouelView () <UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView          *scroll;
@property (nonatomic, strong) UIPageControl         *pageControl;

@property (nonatomic, strong) NSTimer               *timer;


@property (nonatomic, assign) ZKRatio               sizeRatioForMain;
@property (nonatomic, assign) ZKRatio               ratioBetweenMainAndOther;
@property (nonatomic, assign) NSInteger             numOfPages;
@property (nonatomic, assign) NSInteger             numOfScrollPages;
@property (nonatomic, assign) ZKPageControlPosition pageControlPosition;

@end

@implementation ZKPageCarsouelView

- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}


#pragma mark - 懒加载
- (NSInteger)numOfPages {
    
    return [self.dataSource numOfPagesInCarsouelView:self];
}
- (NSInteger)numOfScrollPages {
    
    return self.numOfPages == 1 ? 1 : self.numOfPages * 3;
}
- (ZKRatio)sizeRatioForMain {
    
    if ([self.dataSource respondsToSelector:@selector(sizeRatioForMainInCarsouelView:)]) {
        return [self.dataSource sizeRatioForMainInCarsouelView:self];
    } else {
        ZKRatio ratio;
        ratio.ratio1 = 1;
        ratio.ratio2 = 1;
        return ratio;
    }
}
- (ZKRatio)ratioBetweenMainAndOther {
    
    if ([self.dataSource respondsToSelector:@selector(ratioBetweenMainAndOtherInCarsouelView:)]) {
        return [self.dataSource ratioBetweenMainAndOtherInCarsouelView:self];
    } else {
        ZKRatio ratio;
        ratio.ratio1 = 1;
        ratio.ratio2 = 1;
        return ratio;;
    }
}

- (UIScrollView *)scroll {
    
    if (!_scroll) {
        CGFloat x, y, width, height;
        width = self.width * self.sizeRatioForMain.ratio1;
        height = self.height * self.sizeRatioForMain.ratio2;
        x = (self.width - width) / 2;
        y = (self.height - height) / 2;
        _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(x, y, width, height)];
        _scroll.clipsToBounds = NO;
        _scroll.pagingEnabled = YES;
        _scroll.showsVerticalScrollIndicator = NO;
        _scroll.showsHorizontalScrollIndicator = NO;
        _scroll.delegate = self;
        [self addSubview:_scroll];
    }
    return _scroll;
}
- (ZKPageControlPosition)pageControlPosition {
    
    if ([self.dataSource respondsToSelector:@selector(pageControlPositionInCarsouelView:)]) {
        return [self.dataSource pageControlPositionInCarsouelView:self];
    }
    return bottom_center;
}
- (UIPageControl *)pageControl {
    
    if ([self.dataSource respondsToSelector:@selector(pageControlInCarsouelView:)] && !_pageControl) {
        _pageControl = [self.dataSource pageControlInCarsouelView:self];
        
        switch (self.pageControlPosition) {
            case top_left:
            {
                _pageControl.left = 0;
                _pageControl.top = 0;
            }
                break;
            case top_center:
            {
                _pageControl.x = self.width / 2;
                _pageControl.top = 0;
            }
                break;
            case top_right:
            {
                _pageControl.right = self.width;
                _pageControl.top = 0;
            }
                break;
            case bottom_left:
            {
                _pageControl.left = 0;
                _pageControl.bottom = self.height;
            }
                break;
            case bottom_center:
            {
                _pageControl.x = self.width / 2;
                _pageControl.bottom = self.height + 14;
            }
                break;
            case bottom_right:
            {
                _pageControl.right = self.width;
                _pageControl.bottom = self.height;
            }
                break;
            default:
                break;
        }
    }
    return _pageControl;
}
- (NSNumber *)timerDuration {
    
    if (!_timerDuration) {
        _timerDuration = @5;
    }
    return _timerDuration;
}

#pragma mark - 创建视图
- (void)setupSubViews {
    
    // 先移除scroll上的视图
    [self.scroll.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    // 设置滑动范围
    self.scroll.contentSize = CGSizeMake(self.numOfScrollPages * self.scroll.width, 0);
    
    CGFloat x, y, width, height;
    for (int i = 0; i < self.numOfScrollPages; i ++) {
        x = i * self.scroll.width;
        y = 0;
        width = self.scroll.width;
        height = self.scroll.height;
        
        UIView *view = [self.dataSource carsouelView:self viewForPageIndex:i % self.numOfPages];
        view.frame = CGRectMake(x, y, width, height);
        [self.scroll addSubview:view];
    }
   
    CGFloat offsetX = self.numOfScrollPages == 1 ? 0 : (self.numOfPages) * self.scroll.width;
    self.scroll.contentOffset = CGPointMake(offsetX, 0);
    if (self.numOfPages > 1) {
        [self setScrollContentOffset];

    }
    [self setScrollPageViewsRatio];
}

- (void)setupPageControl {
    
    if (!self.pageControl) {
        return;
    }
    [self addSubview:self.pageControl];
    self.pageControl.numberOfPages = self.numOfPages;
    self.pageControl.currentPage = 0;
}

#pragma mark - 定时器方法
- (void)addTimer {
    if (self.numOfPages == 1) {
        return;
    }
    if (self.timer) {
        return;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timerDuration.floatValue target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    
}
- (void)timerAction:(NSTimer *)timer {
    
    [UIView animateWithDuration:1 animations:^{
        self.scroll.contentOffset = CGPointMake(self.scroll.contentOffset.x + self.scroll.width, 0);
    } completion:^(BOOL finished) {
        [self setScrollContentOffset];
        [self setScrollPageViewsRatio];
    }];

}

#pragma mark - 滑动视图代理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [self setScrollPageViewsRatio];

}
// 滑动视图已经停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    [self setScrollContentOffset];
    [self setScrollPageViewsRatio];

}

#pragma mark - 辅助方法
// 设置scroll的contentOffset
- (void)setScrollContentOffset {
    // 已经滑到第3组的第1张了，则切换到第2组的第1张
    if (self.scroll.contentOffset.x >= (self.numOfPages * 2) * self.scroll.width - 0.5 && self.scroll.contentOffset.x <= (self.numOfPages * 2) * self.scroll.width + 0.5) {
        self.scroll.contentOffset = CGPointMake(self.numOfPages * self.scroll.width, 0);
    }
    // 已经滑到第3组的第2张了，则切换到第2组的第2张
    if (self.scroll.contentOffset.x >= (self.numOfPages * 2 + 1) * self.scroll.width - 0.5 &&
        self.scroll.contentOffset.x <= (self.numOfPages * 2 + 1) * self.scroll.width + 0.5) {
        self.scroll.contentOffset = CGPointMake((self.numOfPages + 1) * self.scroll.width, 0);
    }
    // 已经滑到第1组的最后1张了，则切换到第2组的最后1张
    if (self.scroll.contentOffset.x >= (self.numOfPages - 1) * self.scroll.width - 0.5 &&
        self.scroll.contentOffset.x <= (self.numOfPages - 1) * self.scroll.width + 0.5) {
        self.scroll.contentOffset = CGPointMake((self.numOfPages * 2 - 1) * self.scroll.width, 0);
    }
    // 已经滑到第1组的最后第2张了，则切换到第2组的最后第2张
    if (self.scroll.contentOffset.x >= (self.numOfPages - 2) * self.scroll.width - 0.5 &&
        self.scroll.contentOffset.x <= (self.numOfPages - 2) * self.scroll.width + 0.5) {
        self.scroll.contentOffset = CGPointMake((self.numOfPages * 2 - 2) * self.scroll.width, 0);
    }
    
    // 设置分页视图的当前页数显示
    NSInteger curPage = (self.scroll.contentOffset.x - self.numOfPages * self.scroll.width) / self.scroll.width;
    self.pageControl.currentPage = curPage;
}
// 设置scroll子视图的缩放
- (void)setScrollPageViewsRatio {
    
    CGSize minSize = CGSizeMake(self.scroll.bounds.size.width * self.ratioBetweenMainAndOther.ratio1, self.scroll.bounds.size.height * self.ratioBetweenMainAndOther.ratio2);
    CGSize maxSize = self.scroll.bounds.size;
    
    // 遍历滑动视图子视图来设置缩放
    for (int i = 0; i < self.scroll.subviews.count; i ++) {
        UIView *pageView = self.scroll.subviews[i];
        CGPoint center = pageView.center;
        pageView.width = maxSize.width - MIN(fabs(self.scroll.contentOffset.x - pageView.left) / self.scroll.width, 1) * (maxSize.width - minSize.width);
        pageView.height = maxSize.height - MIN(fabs(self.scroll.contentOffset.x - pageView.left) / self.scroll.width, 1) * (maxSize.height - minSize.height);
        pageView.center = center;
    }
}




#pragma mark - 全局方法
- (void)reloadData {
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    self.pageControl = nil;
    self.scroll = nil;
    
    [self setupSubViews];
    [self addTimer];
    [self setupPageControl];
}


@end
